package com.itheima.socket.udp.demo03;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;

public class SendDataThread implements Runnable {

    @Override
    public void run() {

        try{

            // 1. 创建DatagramSocket对象
            DatagramSocket datagramSocket = new DatagramSocket() ;

            // 2. 使用循环不断的接收键盘录入的数据，将数据发送到接收端
            while(true) {

                // 2.1 创建Scanner对象 , 接收键盘录入数据
                Scanner scanner = new Scanner(System.in) ;
                String sendDataInfo = scanner.next();

                // 2.2 创建DatagramPacket对象，封装要发送的数据： public DatagramPacket(byte buf[], int length,InetAddress address, int port)
                byte[] bytes = sendDataInfo.getBytes("UTF-8");
                int length = bytes.length;
                InetAddress inetAddress = InetAddress.getByName("255.255.255.255");// 也可以去使用127.0.0.1
                int port = 9999 ;
                DatagramPacket datagramPacket = new DatagramPacket(bytes , length , inetAddress , port) ;

                // 2.3 调用datagramSocket对象的方法去发送数据
                datagramSocket.send(datagramPacket);

            }

        }catch ( Exception e) {
            e.printStackTrace();
        }


    }

}
